package com.example.test.config;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import cn.hutool.core.map.MapUtil;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.HandshakeImpl1Server;
import org.java_websocket.handshake.ServerHandshake;

public class MyWebSocketClient extends WebSocketClient {

    public MyWebSocketClient(String url) throws URISyntaxException {
        super(new URI(url));
    }

    @Override
    public void onOpen(ServerHandshake shake) {
        System.out.println("握手...");
        for (Iterator<String> it = shake.iterateHttpFields(); it.hasNext(); ) {
            String key = it.next();
            System.out.println(key + ":" + shake.getFieldValue(key));
        }
    }

    @Override
    public void onMessage(String paramString) {
        System.out.println("接收到消息：" + paramString);
    }

    @Override
    public void onClose(int paramInt, String paramString, boolean paramBoolean) {
        System.out.println("关闭...");
    }

    @Override
    public void onError(Exception e) {
        System.out.println("异常" + e);

    }

    public static void main(String[] args) {
        try {
            MyWebSocketClient client = new MyWebSocketClient("ws://192.168.62.133:18011/websocket");
            client.connect();
            while (!client.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {
                System.out.println("还没有打开");
            }
            System.out.println("建立websocket连接");

            client.onOpen(new HandshakeImpl1Server());


            Map map = new HashMap<String, String>();
            map.put("type", "init");
            map.put("nick", "123");
            map.put("room", "123");
            map.put("pwd", "123");

            client.send(map.toString());

//            HashMap<Object, Object> objectObjectHashMap = MapUtil.newHashMap();
//            objectObjectHashMap.put("shiels","1234");
//            objectObjectHashMap.put("type","msg");
//            client.send(objectObjectHashMap.toString());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

}